<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shared Editing App</title>
    <style>
        .cursor {
            position: absolute;
            width: 2px;
            height: 20px;
            background-color: red;
        }
        .custom_cursor {
            background-color: yellow;
        }
        .cursor-container {
            display: flex;
            flex-direction: column;
            align-items: left;
            position: absolute;
            pointer-events: none;
        }
        .cursor-name {
            margin-top: -30px;
            background-color: #ff0000;
            color: white;
            font-size: 14px;
            padding: 4px 8px;
            border-radius: 12px;
            box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.2);
            font-weight: bold;
            opacity: 0.7;
        }
        .cursor-line {
            width: 2px;
            height: 30px;
            background-color: rgba(255, 0, 0, 0.5);
            margin-top: 4px;
            border-radius: 2px;
        }
    </style>
</head>
<body>
    <h1>Shared Editing App</h1>
    <textarea id="document" rows="20" cols="100" style="display:none;"></textarea>
    <form method="post">
        <textarea id="mytextarea">Hello, World!</textarea>
    </form>
    <div id="cursors">
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script src="/static/tinymce/js/tinymce/tinymce.min.js"></script>
    <script>
        const socket = io();
        let userId;
        let userId_short;

        socket.on('assign_id', (data) => {
            userId = data.user_id;
            userId_short = userId.substr(0, 4);
        });

        tinymce.init({
            selector: '#mytextarea',
            plugins: [
                "advlist", "anchor", "autolink", "charmap", "code", "fullscreen", 
                "help", "image", "insertdatetime", "link", "lists", "media", 
                "preview", "searchreplace", "table", "visualblocks"
            ],
            toolbar: "undo redo | styles | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
            setup: function (editor) {
                editor.on('input', function (e) {
                    const content = editor.getContent({ format: 'text' }).trim();
                    socket.emit('update_document', content);
                    console.log(e)
                });

                editor.on('click keyup', function () {
                    const cursorPosition = editor.selection.getRng().startOffset;
                    socket.emit('update_cursor', { user_id: userId, position: cursorPosition });
                    highlightCursorPosition(editor, userId);
                });
            }
        });

        socket.on('update_cursor', (data) => {
            highlightCursorPosition(tinymce.get('mytextarea'), data.user_id, data.position);
        });

        function highlightCursorPosition(editor, userId, position) {
            const cursorContainer = document.getElementById(`cursor-container-${userId}`);
            if (!cursorContainer) {
                createCursorContainer(userId);
            }
            const cursorPosition = getCursorPosition(editor, position);
            const cursorPositionRect = cursorPosition.getBoundingClientRect();
            const tinymceBody = document.querySelector('iframe[id*="mytextarea_ifr"]');
            const cursorParentPositionRect = tinymceBody.getBoundingClientRect();

            const cursor = document.getElementById(`cursor-container-${userId}`);
            cursor.style.left = cursorPositionRect.left + cursorParentPositionRect.left + 'px';
            cursor.style.top = cursorPositionRect.top + cursorParentPositionRect.top + 'px';
        }

        function getCursorPosition(editor, position) {
            const range = editor.selection.getRng();
            const element = range.endContainer.nodeType === 3 ? range.endContainer.parentNode : range.endContainer;
            return element;
        }

        function createCursorContainer(userId) {
            const cursorsDiv = document.getElementById('cursors');
            const cursorContainer = document.createElement('div');
            cursorContainer.id = `cursor-container-${userId}`;
            cursorContainer.className = 'cursor-container';

            const cursorName = document.createElement('div');
            cursorName.className = 'cursor-name';
            cursorName.textContent = userId_short;

            const cursorLine = document.createElement('div');
            cursorLine.className = 'cursor-line';

            cursorContainer.appendChild(cursorName);
            cursorContainer.appendChild(cursorLine);
            cursorsDiv.appendChild(cursorContainer);
        }
    </script>
</body>
</html>
